import React, { useState, useEffect } from 'react';
import { Modal, Form, Button, Input, Select, InputNumber, Upload } from 'antd';
import { ProFormUploadButton } from '@ant-design/pro-form';
import { upload } from '@/services/ant-design-pro/apis';
import { UploadOutlined } from '@ant-design/icons';
import { message } from 'antd';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

const UpdateProduct = (props) => {
  // const { getFieldDecorator } = props;

  const formLayout = {
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 15,
    },
  };

  const { onSubmit: handleUpdate, onCancel: handleModalVisible, updateModalVisible } = props;

  const [formVals, setFormVals] = useState({
    id: props.values.id,
    // productName: props.values.productName,
    // productNum: props.values.productNum,
    // inventory: props.values.inventory,
    // primeCost: props.values.primeCost,
    // sellingPrice: props.values.sellingPrice,
    // classifyId: props.values.classifyId,
    status: props.values.status,
    productPrice: props.values.productPrice,
    userPrice: props.values.userPrice,
    ownPrice: props.values.ownPrice,
    productImg: props.values.productImg,
  });

  const classifys = props.classifys;

  const handleSubmit = async () => {
    try {
      const fieldVlas = await form.validateFields();
      // fieldVlas.productImg = fileName;
      handleUpdate({ ...fieldVlas });

      setFileList([]);
      setUploaded(false);

      onReset();
    } catch (err) {
      console.log(err);
    }
  };

  const onReset = () => {
    form.resetFields();
  };

  // 处理返回结果
  function normFile(e) {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }

  const [uploaded, setUploaded] = useState(false);
  const [fileList, setFileList] = useState([]);
  const [fileName, setFileName] = useState('');

  // useEffect(() => {
  //   // 根据 formVals.productPicture 设置 fileList 的初始值
  //   if (formVals.productImg.trim() !== '') {
  //     setFileName(formVals.productImg);
  //     setFileList([
  //       {
  //         uid: '1',
  //         name: formVals.productImg,
  //         status: 'done',
  //         url: formVals.productImg,
  //       },
  //     ]);
  //   } else{
  //     setFileList([])
  //   }
  // }, [formVals.productImg]);

  // 文件上传
  const handleCustomRequest = ({ file, onSuccess, onError }) => {
    const formData = new FormData();
    formData.append('uploadfile', file);

    // 执行自定义上传请求
    fetch('/api/product/image', {
      method: 'POST',
      body: formData,
    })
      .then((response) => response.json())
      .then((data) => {
        // 处理响应
        console.log(data);
        onSuccess(data, file);
        setFileName(data.data.split('\\')[5]);
      })
      .catch((error) => {
        // 处理错误
        onError(error, file);
      });
  };

  // 上传之前处理图片
  function beforeUpload(file) {
    const isImage = file.type.startsWith('image/');

    if (!isImage) {
      message.error('只能上传图片文件！', 2);
      return false;
    }
    if (uploaded) {
      message.error('只能上传一张图片', 2);
      return false;
    }

    setUploaded(true);

    const newFileList = [...fileList, file];
    setFileList(newFileList);
    return isImage;
  }

  const [form] = Form.useForm();

  return (
    <Modal
      title="配置产品"
      width={540}
      visible={updateModalVisible}
      destroyOnClose
      onCancel={() => {
        onReset();
        handleModalVisible(false);
      }}
      footer={[
        <Button
          key="reset"
          onClick={() => {
            handleModalVisible();
          }}
        >
          取消
        </Button>,
        <Button
          type="primary"
          key="submit"
          onClick={() => {
            handleSubmit();
          }}
        >
          提交
        </Button>,
      ]}
    >
      <Form
        {...formLayout}
        initialValues={{
          // productName: formVals.productName,
          // productNum: formVals.productNum,
          // inventory: formVals.inventory,
          // primeCost: formVals.primeCost,
          // sellingPrice: formVals.sellingPrice,
          // classifyId: formVals.classifyId,
          productPrice: formVals.productPrice,
          userPrice: formVals.userPrice,
          ownPrice: formVals.ownPrice,
          status: formVals.status,
          productImg: formVals.productImg,
          file: formVals.productImg
            ? [
                {
                  uid: '1',
                  name: formVals.productImg,
                  status: 'done',
                  url: `/product-picture/` + formVals.productImg,
                },
              ]
            : undefined, // 如果productImg不存在，将file设置为undefined
        }}
        form={form}
      >
        {/* <FormItem
          label="产品名称"
          name="productName"
          rules={[
            {
              required: true,
              message: '产品名称是必须项',
            },
          ]}
        >
          <Input placeholder="请输入产品名称"></Input>
        </FormItem> */}
        {/* <FormItem
          label="产品编码"
          name="productNum"
          rules={[
            {
              required: true,
              message: '产品编码是必须项',
            },
          ]}
        >
          <Input placeholder="请输入产品编码" rows={4} />
        </FormItem> */}
        {/* <FormItem
          label="库存数量"
          name="inventory"
          rules={[
            {
              required: true,
              message: '库存数量是必须项',
            },
          ]}
        >
          <InputNumber placeholder="请输入库存数量" style={{ width: '100%' }} />
        </FormItem> */}
        {/* <FormItem
          label="官网价格(元)"
          name="productPrice"
          rules={[
            {
              required: true,
              message: '官网价格是必须项',
            },
          ]}
        >
          <InputNumber placeholder="请输入官网价格" style={{ width: '100%' }} />
        </FormItem>
        <FormItem
          label="售卖价格(元)"
          name="userPrice"
          rules={[
            {
              required: true,
              message: '售卖价格是必须项',
            },
          ]}
        >
          <InputNumber placeholder="请输入售卖价格" style={{ width: '100%' }} />
        </FormItem> */}
        <FormItem
          label="自己价格(元)"
          name="ownPrice"
          rules={[
            {
              required: true,
              message: '自己价格是必须项',
            },
          ]}
        >
          <InputNumber placeholder="请输入自己价格" style={{ width: '100%' }} />
        </FormItem>

        {/* <FormItem label="类型" name="classifyId">
          <Select placeholder="请选择类型">
            {classifys?.map((item) => {
              return <Option value={item.id}>{item.typeName}</Option>;
            })}
          </Select>
        </FormItem> */}

        <FormItem label="状态" name="status">
          <Select>
            <Option value={'PUTAWAY'}>上架</Option>
            <Option value={'DELIST'}>下架</Option>
          </Select>
        </FormItem>

        {/* <Form.Item
          label="产品图片"
          name="file"
          valuePropName="fileList"
          getValueFromEvent={normFile}
          rules={[
            {
              required: true,
              message: '请上传产品图片',
            },
          ]}
        >
          <Upload
            name="uploadfile"
            listType="picture-card"
            customRequest={handleCustomRequest}
            action="/api/product/image" // 上传图片的服务端接口
            beforeUpload={beforeUpload}
            onRemove={onRemove}
          >
            {fileList.length > 0 ? null : <Button icon={<UploadOutlined />}>点击上传</Button>}
          </Upload>
        </Form.Item> */}
      </Form>
    </Modal>
  );
};

export default UpdateProduct;
